#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
using namespace std;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR,
    LISTEN_ERROR,
};
const static int defaultsockfd = -1;
const static int gbacklog = 16;
class TcpServer
{
public:
    TcpServer(uint16_t port) : _port(port), _listensock(defaultsockfd), _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建流式套接字
        //_sockfd = socket(AF_INET, SOCK_DGRAM, 0);udp
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "sockfd error,%s,%d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success,socket:%d\n", _listensock);
        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%s,%d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind create success\n");
        // tcp是面向连接的，所以再通信之前必须先建立连接
        // tcp 启动，未来首先要一直等待客户的连接到来
        // 监听
        n = listen(_listensock, gbacklog);
        if (n < 0)
        {
            LOG(FATAL, "listen error,%s,%d\n", strerror(errno), errno);
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen create success\n");
    }
    void Loop() // 循环
    {
        _isrunning = true;
        // 不能直接接受数据，要先获取连接
        // 连接用 accept
        while (_isrunning)
        {
            struct sockaadr_in peer;
            socklen_t len = sizeof(peer);
            int _sockfd = accept(_listensock, (struct sockaadr *)&peer, &len);
            if(_sockfd<0)
            {

            }
        }
    }
    ~TcpServer()
    {
    }

private:
    int _listensock;
    uint16_t _port;
    bool _isrunning;
};